package com.giggle.nacos.registry.dubbo;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.giggle.nacos.helper.NacosHelper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (这里用一句话描述累的作用)
 * @date 2020/8/26 17:54
 */
public class NacosRegistryFactory extends AbstractRegistryFactory {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public NacosRegistryFactory() {
    }

    @Override
    protected Registry createRegistry(URL url) {
        url = NacosHelper.handleUrl(url);
        return new NacosRegistry(url, this.buildNamingService(url));
    }

    private NamingService buildNamingService(URL url) {
        Properties nacosProperties = this.buildNacosProperties(url);

        try {
            NamingService namingService = NacosFactory.createNamingService(nacosProperties);
            return namingService;
        } catch (NacosException var5) {
            if (this.logger.isErrorEnabled()) {
                this.logger.error(var5.getErrMsg(), var5);
            }

            throw new IllegalStateException(var5);
        }
    }

    private Properties buildNacosProperties(URL url) {
        Properties properties = new Properties();
        this.setServerAddr(url, properties);
        this.setProperties(url, properties);
        return properties;
    }

    private void setServerAddr(URL url, Properties properties) {
        NacosHelper.handleUrl(url);
        StringBuilder serverAddrBuilder = (new StringBuilder(url.getHost())).append(":").append(url.getPort());
        String backup = url.getParameter("backup");
        if (backup != null) {
            serverAddrBuilder.append(",").append(backup);
        }

        String serverAddr = serverAddrBuilder.toString();
        properties.put("serverAddr", serverAddr);
    }

    private void setProperties(URL url, Properties properties) {
        this.putPropertyIfAbsent(url, properties, "com.alibaba.nacos.naming.log.filename");
        this.putPropertyIfAbsent(url, properties, "endpoint");
        this.putPropertyIfAbsent(url, properties, "accessKey");
        this.putPropertyIfAbsent(url, properties, "secretKey");
        this.putPropertyIfAbsent(url, properties, "clusterName");
        NacosHelper.putByNacosProperties(url, properties);
    }

    private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) {
        String propertyValue = url.getParameter(propertyName);
        if (propertyValue != null && propertyValue.trim().length() != 0) {
            properties.setProperty(propertyName, propertyValue);
        }

    }
}

